package com.flea.service;

import com.flea.model.Product;
import com.flea.repository.es.ProductDocRepository;
import com.flea.repository.jdbc.ProductRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.support.PageableExecutionUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author hc24
 * @date 2021.1.21 13:29
 */
@Service
public class ProductService {

    @Resource
    private ProductRepository productRepository;

    @Resource
    private ProductDocRepository productDocRepository;

    @Resource
    private JdbcTemplate jdbcTemplate;

    /**
     * 根据关键字进行商品搜索
     *
     * @return
     */
    public Page<Product> search(String key, Pageable pageable) {
        if (key == null) {
            key = "";
        }
        key = "%" + key + "%";
        // select * from product where name like ? or desc like ?
//        List<Product> list = productRepository.findByNameLikeOrDescLike(key, key, pageable);
//        long total = productRepository.countByNameLikeOrDescLike(key, key);
//        return PageableExecutionUtils.getPage(list, pageable, () -> total);
        return productRepository.findByNameLikeOrDescLike(key, key, pageable);
    }

    /**
     * 获取最新的产品
     *
     * @param pageable
     * @return
     */
    public Page<Product> findLatest(Pageable pageable) {
        List<Product> productList = productRepository.findByOrderByCreateTimeDesc(pageable);
        long total = productRepository.count();
        return PageableExecutionUtils.getPage(productList, pageable, () -> total);
    }

    public void del(Integer id) {

        productRepository.deleteById(id);
    }


    public void create(Product product) {
        productRepository.save(product);
        productDocRepository.save(product.toDoc());
    }

    public void testSql() {

    }

}
